<template>
    <div id='wrap'>
        <button @click="createTimer">添加定时器</button>
        <div v-for="(item, index) in times" :key="index">
            <p>{{ index + 1 }}{{ item.time }}</p>
        </div>
    </div>
</template>
<script lang='ts'>
export default {
    name: 'vue',
}
</script>
<script lang='ts' setup>
import { ref, h, type Ref, isRef, reactive, isReactive, readonly, isReadonly, toRef, toRefs, unref, isProxy, EffectScope, effectScope, onScopeDispose } from 'vue';
interface ClassB {
    time: Ref<number>,
    scope: EffectScope
}
function userTimer(): ClassB {
    const time = ref(0);
    let interval: ReturnType<typeof setInterval>;
    const scope = effectScope();
    scope.run(() => {
        interval = setInterval(() => {
            time.value++;
        }, 1000)
        //在作用域销毁时清除定时器
        onScopeDispose(() => {
            clearInterval(interval);
            console.log('计时器停止，资源被清理');
        })
    })
    return { time, scope }
}
//管理多个定时器
type TimeRef = Ref<ClassB[]>
const times: TimeRef = ref([]);
//创建一个函数 创建定时器
function createTimer() {
    const newTimer: ClassB = userTimer();
    times.value.push(newTimer);
}

//移出计时器
function removeitem(index: number) {
    times.value[index].scope.stop();
    times.value.splice(index, 1);
}
</script>
<style lang='scss'>
@use '@/assets/common.scss';
</style>